package com.lancoo.rxretrofitlibrary.exception;


import com.google.gson.JsonSyntaxException;
import com.lancoo.reviewsystem.utils.TimeUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import rx.Observable;
import rx.functions.Func1;

import static com.lancoo.reviewsystem.utils.TimeUtils.SERVER_DATE_FORM1;

/**
 * Created by tangminglong on 17/11/17.
 */

public class RetryWithDelay implements Func1<Observable<? extends Throwable>, Observable<?>> {

    private final int maxRetries;
    private final int retryDelayMillis;
    private final int retryIncreaseDelay;
    private int retryCount;

    public RetryWithDelay(int maxRetries, int retryDelayMillis,int retryIncreaseDelay) {
        this.maxRetries = maxRetries;
        this.retryDelayMillis = retryDelayMillis;
        this.retryIncreaseDelay = retryIncreaseDelay;
    }


    @Override
    public Observable<?> call(Observable<? extends Throwable> attempts) {

        return attempts.flatMap(new Func1<Throwable, Observable<?>>() {
            @Override
            public Observable<?> call(Throwable throwable) {
                if (( throwable instanceof ConnectException
                        || throwable instanceof SocketTimeoutException
                        || throwable instanceof TimeoutException)
                        && ++retryCount <= maxRetries) { //如果超出重试次数也抛出错误，否则默认是会进入onCompleted}
                    return Observable.timer(retryDelayMillis + (retryCount - 1)*retryIncreaseDelay, TimeUnit.MILLISECONDS);
                }else {
                    return Observable.error(throwable);
                }


            }
        });

    }
}
